package com.yrmao.chiefenergyofficer.ui.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;

import com.yrmao.chiefenergyofficer.R;
import com.yrmao.chiefenergyofficer.ui.adapter.MPagerAdapter;
import com.yrmao.chiefenergyofficer.ui.carousel.FixedSpeedScroller;
import com.yrmao.chiefenergyofficer.ui.common.BaseFragment;
import com.yrmao.chiefenergyofficer.utils.HanderUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by sikong on 16/11/16.
 */

public class ItemCarouselFragment extends BaseFragment {
    private MPagerAdapter mPagerAdapter;
    private View contentView;
    private ViewPager mViewPager;
    private List<Integer> imglist;
    private HanderUtil handerUtil;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        contentView = LayoutInflater.from(getActivity()).inflate(R.layout.frag_carousel, null);
        initData();
        initView(contentView);
        try {
            initViewPager();
        } catch (Exception e) {
            e.printStackTrace();
        }
        handerUtil.startHander();

    }

    private void initData() {
        imglist = new ArrayList<>();
        imglist.add(R.mipmap.carousel_main1);
        imglist.add(R.mipmap.carousel_main2);
        imglist.add(R.mipmap.carousel_main3);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return contentView;

    }

    private void initView(View view) {

        mViewPager = (ViewPager) view.findViewById(R.id.vp_carouse);
        mPagerAdapter = new MPagerAdapter(getActivity(), imglist);
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setCurrentItem(Integer.MAX_VALUE / 2);
        handerUtil = new HanderUtil(getActivity());
        handerUtil.setRunnableTime(5 * 1000);
        handerUtil.setViewPager(mViewPager);
    }

    private void initViewPager() throws Exception {
//        mViewPager.setPageTransformer(true, new DepthPageTransformer());//设置转动动画
        Field field = ViewPager.class.getDeclaredField("mScroller");
        field.setAccessible(true);
        FixedSpeedScroller scroller = new FixedSpeedScroller(getActivity(), new AccelerateInterpolator());
        field.set(mViewPager, scroller);
        scroller.setmDuration(500);//设置缓冲时间
    }

    @Override
    public void onStart() {
        super.onStart();
        handerUtil.startHander();
    }

    @Override
    public void onPause() {
        super.onPause();
        handerUtil.pauseHander();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handerUtil.stopHander();
    }
}
